<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_wx_os\controller;
use cmf\controller\PluginAdminBaseController;
use plugins\qbt_wx_os\model\WxOsConfigModel;
use plugins\qbt_wx_os\model\WxOsReplyModel;
use plugins\qbt_wx_os\model\WxOsMenuModel;
use plugins\qbt_wx_os\model\WxOsGMenuModel;
use think\Validate;
use think\Db;

class AdminIndexController extends PluginAdminBaseController
{
    public function _initialize()
    {
        $this->data = input();
        $this->wocmodel = new WxOsConfigModel();
        $this->wormodel = new WxOsReplyModel();
        $this->wommodel = new WxOsMenuModel();
        $this->wogmodel = new WxOsGMenuModel();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            $this->error('未登录');
        }
    }


    /**
     * 微信公众号管理
     * @adminMenu(
     *     'name'   => '微信公众号管理',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '千佰特微信公众号管理',
     *     'param'  => ''
     * )
     */
    //首页(微信公众号配置)
    public function index(){
        // $http = $_SERVER['REQUEST_URI'];

        // preg_match('/(.*?)plugin.*?/',$http,$m);
        // $info = $this->wocmodel->data_list();
        // $info['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$m[0].'/qbt_wx_os/wx_reply/valid';
        // $this->assign('info',$info);
        $info = $this->wocmodel->data_list();
        //if(empty($info)){$this->error('请先完善公众号信息！');}
        $id = isset($this->data['id'])?$this->data['id']:0;
        if(!empty($id)){$g_id = $id;}else{$g_id = 0;}
        if(isset($this->data['name'])){$this->assign('name',$this->data['name']);}
        $p_list = $this->wommodel->data_list('p_id = 0 and g_id = '.$g_id);
        $this->assign('p_list',$p_list);
        $list = $this->wommodel->data_list('p_id != 0 and g_id = '.$g_id);
        $this->assign('list',$list);
        $this->assign('g_id',$id);
        return $this->fetch('/menu');
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/edit_action|编辑微信公众号配置信息:{wx_name}',
     * )
     */
    public function edit_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
       $info = $this->wocmodel->data_list();
       //不为空就走更改程序，为空就走添加程序
        $this->check_data($this->data,'WxOsConfig');
       if(!empty($info)){
           $status = $this->wocmodel->update_data('id ='.$this->data['id'],$this->data);
           $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/index'));
       }else{
            //添加
            $status = $this->wocmodel->add_data($this->data);
            $this->data_action($status,'add',cmf_plugin_url('QbtWxOs://AdminIndex/index'));
       }
    }




    //公众号关注欢迎词
    //微信公众号欢迎语
    public function reply(){
        $info = $this->wocmodel->data_list();
        //if(empty($info)){$this->error('请先完善公众号信息！');}
        $info = $this->wormodel->data_info('type = 9');
        $this->assign('info',$info);
        return $this->fetch('/reply');
    }


    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/attens_action|编辑微信公众号欢迎词:{str}',
     * )
     */
    public function attens_action(){
        $info = $this->wormodel->data_info('type = 9');
        $arr['str'] = $this->data['str'];
        $arr['type'] = 9;
        if(!empty($info)){
            //不为空做更改操作
            $status = $this->wormodel->update_data('type = 9',$arr);
            $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/reply'));
        }else{
            //为空做添加操作
            $status = $this->wormodel->add_data($arr);
            $this->data_action($status,'add',cmf_plugin_url('QbtWxOs://AdminIndex/reply'));
        }
    }




    //公众号关键词管理：文字，图片，图文
    //关键词回复列表
    public function keyword_reply(){
        $list = $this->wormodel->data_list('type != 9');
        $this->assign('list',$list);
        return $this->fetch('/keyword_reply');
    }

    //增加关键词
    public function add_keyword(){

        return $this->fetch('/add_keyword');
    }

    //修改状态
    public function setstatus(){
        $id = $this->data['id'];
        $status = $this->data['status'];
        $where = array();
        $data = array();
        $where['id'] = $id;
        $data['status'] = $status;
        $status = $this->wormodel->update_data($where,$data);
        $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/keyword_reply'));
    }


    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/add_keyword_action|增加微信公众号关键字:{keyword}',
     * )
     */
    public function add_keyword_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        $this->validate_data($this->data);
        $media_id = $this->upload_image($this->data);
        $data = $this->r_data($this->data);
        $data['media_id'] = $media_id;
        $status = $this->wormodel->add_data($data);
        $this->data_action($status,'add',cmf_plugin_url('QbtWxOs://AdminIndex/keyword_reply'));
    }

     //详情
    public function info(){
        $where['id'] = $this->data['id'];
        $info = $this->wormodel->data_info($where);
        if($info['type'] == 2){
            $info['img'] = json_decode($info['image'],true);
        }else if($info['type'] == 3){
            $info['img_str'] = json_decode($info['img_str'],true);
        }
        $this->assign('info',$info);
        return $this->fetch('/info');
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/edit_keyword_action|修改微信公众号关键字:{keyword}',
     * )
     */
    public function edit_keyword_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        $this->validate_data($this->data);
        $media_id = $this->upload_image($this->data);
        $data = $this->r_data($this->data);
        $where['id'] = $this->data['id'];
        $data['media_id'] = $media_id;
        $status = $this->wormodel->update_action($where,$data);
        $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/keyword_reply'));
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/del|删除微信公众号关键字:{id}',
     * )
     */
    public function del(){
        $where['id'] = $this->data['id'];
        $status = $this->wormodel->del_data($where);
        $this->data_action($status,'del',cmf_plugin_url('QbtWxOs://AdminIndex/keyword_reply'));
    }

   




    //自定义菜单部分，分默认菜单和个性菜单
    //自定义菜单
    public function menu_list(){
        $info = $this->wocmodel->data_list();
        //if(empty($info)){$this->error('请先完善公众号信息！');}
        $list = $this->wogmodel->data_list();
        $data = $list->items();
        $data = $this->toarray($data);
        $c_list = Db::name('wx_os_city')->select()->toArray();
        foreach($data as $k=>$v){
            foreach($c_list as $key=>$val){
                if($v['cid'] == $val['cid'] && $v['pid'] == $val['pid']){
                    $data[$k]['c_name'] = $val['city'];
                }
            }
        }
        $lan_list = $this->lan();
        
        foreach($data as $k=>$v){
            $data[$k]['lan_name'] = "";
            foreach($lan_list as $key=>$val){
                if($v['lan'] == $key){
                    $data[$k]['lan_name'] = $val;
                }
            }
        }

        $this->assign('page',$list->render());
        $this->assign('list',$data);
        return $this->fetch('/menu_list');
    }


    public function add_mat_menu(){
        $p_list = Db::name('wx_os_provincial')->select()->toArray();
        $this->assign('p_list',$p_list);
        $l_list = $this->lan();
        $this->assign('l_list',$l_list);
        return $this->fetch('/add_mat_menu');
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/add_mat_menu_action|增加新的个性菜单栏:{name}',
     * )
     */
    public function add_mat_menu_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        if(empty($this->data['name'])){
            $this->error('个性菜单名称不能为空');
        }
        if(isset($this->data['sex'])){
            $where['sex'] = $this->data['sex'];
        }
        if(isset($this->data['sex'])){
            $where['os_type'] = $this->data['os_type'];
        }
        $where['country'] = $this->data['country'];
        $where['pid'] = $this->data['pid'];
        $where['cid'] = $this->data['cid'];
        $where['lan'] = $this->data['lan'];
        $info = $this->wogmodel->data_info1($where);
        if(!empty($info)){
            $this->error('已存在该类型的个性菜单栏');
        }
        $this->data['add_time'] = time();
        $this->data['status'] = 0;
        $status = $this->wogmodel->add_data($this->data);
        $this->data_action($status,'add',cmf_plugin_url('QbtWxOs://AdminIndex/menu_list'));
    }


    public function edit_mat_menu(){
        $info = $this->wogmodel->data_info('id ='.$this->data['id']);
        $c_list = Db::name('wx_os_city')->where('pid ='.$info['pid'])->select()->toArray();
        $p_list = Db::name('wx_os_provincial')->select()->toArray();
        $this->assign('p_list',$p_list);
        $l_list = $this->lan();
        $this->assign('l_list',$l_list);
        $this->assign('info',$info);
        $this->assign('c_list',$c_list);
        return $this->fetch('/edit_mat_menu');
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/edit_mat_menu|编辑个性菜单栏:{name}',
     * )
     */
    public function adit_mat_menu_action(){

        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        if(empty($this->data['name'])){
            $this->error('个性菜单名称不能为空');
        }
        if(isset($this->data['sex'])){
            $where['sex'] = $this->data['sex'];
        }
        if(isset($this->data['sex'])){
            $where['os_type'] = $this->data['os_type'];
        }
        $where['name'] = $this->data['name'];
        $where['country'] = $this->data['country'];
        $where['pid'] = $this->data['pid'];
        $where['cid'] = $this->data['cid'];
        $where['lan'] = $this->data['lan'];
        $info = $this->wogmodel->data_info1($where);
        if($info['id'] != $this->data['id']){
            if(!empty($info)){
                $this->error('已存在该类型的个性菜单栏');
            }
        }
        $this->data['add_time'] = time();
        $where1['id'] = $this->data['id'];
        $status = $this->wogmodel->update_data($where1,$this->data);
        $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/menu_list'));
    }

    //获取城市
    public function get_city(){
        $pid = $this->data['pid'];
        $c_list = Db::name('wx_os_city')->where('pid ='.$pid)->select()->toArray();
        if($c_list[0]['city'] == ''){
            $c_list['status'] = 0;
        }
        echo json_encode($c_list);
    }

    public function menu(){        
        $info = $this->wocmodel->data_list();
        //if(empty($info)){$this->error('请先完善公众号信息！');}
        $id = isset($this->data['id'])?$this->data['id']:0;
        if(!empty($id)){$g_id = $id;}else{$g_id = 0;}
        if(isset($this->data['name'])){$this->assign('name',$this->data['name']);}
        $p_list = $this->wommodel->data_list('p_id = 0 and g_id = '.$g_id);
        $this->assign('p_list',$p_list);
        $list = $this->wommodel->data_list('p_id != 0 and g_id = '.$g_id);
        $this->assign('list',$list);
        $this->assign('g_id',$id);
        return $this->fetch('/menu');
    }


    public function add_menu(){
        $arr = $this->menu_type_arr();
        $this->assign('arr',$arr);
        $list = $this->wommodel->data_list('p_id = 0 and g_id ='.$this->data['g_id']);
        $this->assign('list',$list);
        if($this->data['g_id'] != 0){
            $info = $this->wogmodel->data_info('id ='.$this->data['g_id']);
            $this->assign('name',$info['name']);
        }
        $this->assign('g_id',$this->data['g_id']);
        return $this->fetch('/add_menu');
    }

    //线上菜单栏
    public function online_menu(){
        $lists = Db::name('plugin')->where(['name'=>'QbtWxOs'])->find();
        $fosn = $lists['config'];
        $info = json_decode($fosn,true);
        if(empty($info['appid']) || empty($info['appsecret'])){
            $this->error('请先填写配置信息',cmf_plugin_url('QbtWxOs://AdminIndex/menu'));
        }

        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$access_token;
        $info = $this->curl($url);
        $info = json_decode($info,true);
        // var_dump($info);
        $list = $info['menu']['button'];
        $this->assign('list',$list);
        $this->assign('g_id',0);
        return $this->fetch('/online_menu');

    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/add_menu_action|增加菜单栏:{menu_name}',
     * )
     */
    public function add_menu_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        //数据验证

        $where['g_id'] = $this->data['g_id'];
        $this->check_menu_data($this->data);
        if($this->data['p_id'] == 0){
            $field = 'count(id) as count';
            $where['p_id'] = 0;
            $info = $this->wommodel->data_field($field,$where);
            $this->data['lv_type'] = 1;
            if($info['count'] > 2){
                $this->error('抱歉，一级菜单最多是3个');
            }
        }else{
            $this->data['lv_type'] = 2;
            $field = 'count(id) as count';
            $where['p_id'] = $this->data['p_id'];
            $info = $this->wommodel->data_field($field,$where);
            if($info['count'] > 4){
                $this->error('抱歉，该级菜单最多是5个');
            }
        }
        $this->data['add_time'] = time();
        //数据整理

        $data = $this->check_admenu_data($this->data);

        $status = $this->wommodel->add_data($data);
        $this->data_action($status,'add',cmf_plugin_url('QbtWxOs://AdminIndex/menu',['id'=>$this->data['g_id']]));
    }


    public function edit_menu(){
        $info = $this->wommodel->data_info('id ='.$this->data['id']);
        //编辑数据处理
        $data = $this->edit_data_rest($info);
        $data = $this->toarray($data);
        $this->assign('info',$data);
        $arr = $this->menu_type_arr();
        $this->assign('arr',$arr);
        $list = $this->wommodel->data_list('p_id = 0');
        $this->assign('list',$list);
        return $this->fetch('/edit_menu');
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/del_g_menu|删除个性菜单栏:{id}',
     * )
     */
    public function del_g_menu(){
        $info = $this->wogmodel->data_info('id ='.$this->data['id'])->toArray();
        if(empty($info['content'])){$this->error('该个性菜单并没有添加到微信服务器上');}
        $data['menuid'] = $info['content'];
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=".$access_token;
        $arr = json_encode($data);
        $result = $this->curl($url, $arr);
        $result_info = json_decode($result,true);
        if($result_info['errcode'] == 0){
            $this->wogmodel->del_data('id ='.$this->data['id']);
            $this->wommodel->del_data('g_id ='.$this->data['id']);
            $this->success('删除成功!');
        }
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/edit_menu_action|编辑菜单栏:{id}',
     * )
     */
    public function edit_menu_action(){
        unset($this->data['_plugin']);
        unset($this->data['_controller']);
        unset($this->data['_action']);
        $this->check_menu_data($this->data);
        $info = $this->wommodel->data_info('id ='.$this->data['id']);
        if($info['p_id'] != $this->data['p_id']){
            if($this->data['p_id'] == 0){
                $field = 'count(id) as count';
                $where['p_id'] = 0;
                $info = $this->wommodel->data_field($field,$where);
                $this->data['lv_type'] = 1;
                if($info['count'] > 2){
                    $this->error('抱歉，一级菜单最多是3个');
                }
            }else{
                $this->data['lv_type'] = 2;
                $field = 'count(id) as count';
                $where['p_id'] = $this->data['p_id'];
                $info = $this->wommodel->data_field($field,$where);
                if($info['count'] > 4){
                    $this->error('抱歉，该级菜单最多是5个');
                }
            }
        }
        $this->data['add_time'] = time();
        $data = $this->check_admenu_data($this->data);
        $where['id'] = $this->data['id'];
        $status = $this->wommodel->update_data($where,$data);
        $this->data_action($status,'update',cmf_plugin_url('QbtWxOs://AdminIndex/menu',['id'=>$info['g_id']]));
    }

    /**
     * @adminLog(
     *     'public/plugin/qbt_wx_os/admin_index/del_menu|删除菜单栏:{id}',
     * )
     */
    public function del_menu(){
        $status = $this->wommodel->del_data('id ='.$this->data['id']);
        $this->data_action($status,'del',cmf_plugin_url('QbtWxOs://AdminIndex/menu'));
    }

    public function if_content($data){
        $str = '';
        if($data == 1){
            $str = 'click';
        }else if($data == 2){
            $str = 'view';
        }
        return $str;
    }

    public function if_key($data){
        $str = '';
        if($data == 'click'){
            $str = 'key';
        }else if($data == 'view'){
            $str = 'url';
        }
        return $str;
    }

    //ajax进行菜单栏更新
    public function gx_menu(){
        $g_id = $this->data['id'];
        $data = '{"button":[';
        $p_list = $this->wommodel->data_list('p_id = 0 and g_id ='.$g_id);
        if(count($p_list) == 0){echo 0;die;}
        //第一级的下级查询
        foreach($p_list as $k=>$v){
            $list = $this->wommodel->data_list('p_id ='.$v['id']);
            if(empty($list)){
                $str = $this->if_content($v['name_type']);
                $key = $this->if_key($str);
                if($str == 'click'){
                    $value = $v['key'];
                }else if($str == 'view'){
                    $value = $v['url'];
                }
                if(count($p_list)-1 == $k){
                     $data .= '{
                        "type":"'.$str.'",
                        "name":"'.$v['menu_name'].'",
                        "'.$key.'":"'.$value.'"
                       }';
                }else{
                    $data .= '{
                        "type":"'.$str.'",
                        "name":"'.$v['menu_name'].'",
                        "'.$key.'":"'.$value.'"
                       },';
                }
               
            }else{
                $data .='{
                   "name":"'.$v['menu_name'].'",
                   "sub_button":[';
                foreach($list as $kk=>$vv){
                    $str1 = $this->if_content($vv['name_type']);
                    $key1 = $this->if_key($str1);
                    if($str1 == 'click'){
                        $value1 = $vv['key'];
                    }else if($str1 == 'view'){
                        $value1 = $vv['url'];
                    }
                    if(count($list)-1 == $kk){
                        $data .= '{
                            "type":"'.$str1.'",
                            "name":"'.$vv['menu_name'].'",
                            "'.$key1.'":"'.$value1.'"
                        }';
                    }else{
                        $data .= '{
                            "type":"'.$str1.'",
                            "name":"'.$vv['menu_name'].'",
                            "'.$key1.'":"'.$value1.'"
                        },';
                    }
                }
                $data .=']
               },';
            }
        }
        $data .= '],';
        if($g_id != 0){
           $info = $this->wogmodel->data_info('id ='.$g_id);

           $data .= '"matchrule":{
                      "sex":"'.$info['sex'].'",
                      "country":"中国",
                      "province":"'.$info['p_name'].'",
                      "city":"'.$info['c_name'].'",
                      "client_platform_type":"'.$info['os_type'].'",
                      "language":"'.$info['lan'].'"
                      }';
        }
        $data .='}';
        $access_token = $this->get_access_token();
        if($g_id != 0){
            $url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$access_token;
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        }
        $result = $this->curl($url, $data);
        $info = json_decode($result,true);
        if(isset($info['errmsg']) == 'ok'){
            echo 1;
        }else if(!empty($info['menuid'])){
            $data1['content'] = $info['menuid'];

            Db::name('wx_os_g_menu')->where('id ='.$g_id)->update($data1);
            echo 1;
        }else{
            echo 0;
        }
    }













    //公共部分
    //菜单类型分类
    public function menu_type_arr(){
        $arr = array(
            0 =>array(
                'type' => 1,
                'name' => '点击事件'
                ),
            1 =>array(
                'type' => 2,
                'name' => '跳转连接'
                ),
            );
        return $arr;
    }

    //语言组
    public function lan(){
        $arr = array(
            'zh_CN'=>'简体中文',
            'zh_TW'=>'繁体中文TW',
            'zh_HK'=>'繁体中文HK',
            'en'=>'英文',
            'id'=>'印尼',
            'ms'=>'马来',
            'es'=>'西班牙',
            'ko'=>'韩国',
            'it'=>'意大利',
            'ja'=>'日本',
            'pl'=>'波兰',
            'pt'=>'葡萄牙',
            'ru'=>'俄国',
            'th'=>'泰文',
            'vi'=>'越南',
            'ar'=>'阿拉伯语',
            'hi'=>'北印度',
            'he'=>'希伯来',
            'tr'=>'土耳其',
            'de'=>'德语',
            'fr'=>'法语',
        );
        return $arr;
    }

    //数据重组
    public function r_data($data){
        $arr = array();
        $arr1 = array();
        $data1 = array();
        $arr['img_url'] = $data['img_url'];
        $arr['img_name'] = $data['img_name'];
        $arr1['title'] = $data['title'];
        $arr1['desc'] = $data['desc'];
        $arr1['url'] = $data['url'];
        $arr1['img_url1'] = $data['img_url1'];
        $arr1['img_name1'] = $data['img_name1'];
        $data1['img_str'] = json_encode($arr1);
        $data1['image'] = json_encode($arr);
        $data1['add_time'] = time();
        $data1['keyword'] = $data['keyword'];
        $data1['str'] = $data['str'];
        $data1['type'] = $data['type'];
        return $data1;
    }

     public function check_data($arr,$str){
        $result = $this->validate($arr,$str);
        if ($result !== true) {
            $this->error($result);
        }
    }

        //菜单数据验证
    public function check_menu_data($data){
        if(empty($data['menu_name'])){
            $this->error('菜单名称不能为空！');
        }
        //验证如果为click事件时，不能key值存在一样的
        if(!empty($data['key'])){
            $where['key'] = $data['key'];
            $info = $this->wommodel->data_info($where);
            if(!empty($info)){
                $this->error('KEY值已存在');
            }
        }
    }

    //手动验证数据
        public function validate_data($data){
        if(empty($data['keyword'])){
            $this->error('关键词不能为空！');
        }
        $keyword = $data['keyword'];
        $info = $this->wormodel->data_info("keyword = '$keyword'");
        if(!empty($info)){$this->error('已存在相关的关键词');}
        if($data['type'] == 1){
            if(empty($data['str'])){
                $this->error('文字回复不能为空！');
            }
        }else if($data['type'] == 2){
            if(empty($data['img_url'])){
                $this->error('图片回复不能为空！');
            }
        }else if($data['type'] == 3){
            if(empty($data['title'])){
                $this->error('标题不能为空！');
            }
            if(empty($data['desc'])){
                $this->error('描述不能为空！');
            }
            if(empty($data['url'])){
                $this->error('跳转地址不能为空！');
            }
            if(empty($data['img_url1'])){
                $this->error('图片不能为空！');
            }
        }
    }

    public function data_action($status,$str,$url=''){
        if($status !== false){
            if($str == 'add'){
                $this->success('保存成功！',$url);
            }else if( $str == 'update'){
                $this->success('更改成功！',$url);
            }else if($str == 'del'){
                $this->success('删除成功！',$url);
            }
        }else{
            $this->error('操作失败！');
        }
    }

    //curl请求的封装
    public function curl($url, $post = '', $cookie = '', $cookiejar = '', $referer = ''){
        $tmpInfo = '';
        $cookiepath = getcwd().'./'.$cookiejar;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_USERAGENT, isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11');
        if($referer) {
            curl_setopt($curl, CURLOPT_REFERER, $referer);
        } else {
            curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        }
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        if($cookiejar) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath);
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath);
        }
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 100);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo '<pre><b>错误:</b><br />'.curl_error($curl);
        }
        curl_close($curl);
        return $tmpInfo;
    }

    public function curl2($url, $type = 'get', $res = 'json', $arr = ''){
        $cl = curl_init();
        curl_setopt($cl, CURLOPT_URL, $url);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
        if($type == 'post'){
            curl_setopt($cl, CURLOPT_POST, 1);
            curl_setopt($cl, CURLOPT_POSTFIELDS, $arr);
        }
        $output = curl_exec($cl);
        curl_close($cl);
        if($res == 'json'){
            if( curl_error($cl)){
                return curl_error($cl);
            }else{
                return json_decode($output, true);
            }
        }
    }

    //获得微信的access_token
    public function get_access_token(){
        //$info = $this->wocmodel->data_list();
        $lists = Db::name('plugin')->where(['name'=>'QbtWxOs'])->find();
        $fosn = $lists['config'];
        $info = json_decode($fosn,true);

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$info['appid']."&secret=".$info['appsecret'];
        $token = $this->curl($url);
        $token = json_decode(stripslashes($token));
        $arr = json_decode(json_encode($token), true);

        $access_token = $arr['access_token'];
        return $access_token;
    }

        //图片上传到微信素材库
    public function upload_image($data){
        //先判断type是否位image
        if($data['type'] == 2){
            $access_token = $this->get_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=image";
            $tt_url = $_SERVER['PHP_SELF'];
            $fine_name = ltrim(dirname($tt_url),'/');
            $real_path = $_SERVER['DOCUMENT_ROOT'].$fine_name .'/upload/'.$data['img_url'];

            $data = array("filename" =>new \CURLFile($real_path));
            $info = $this->curl($url,$data);
            $info = json_decode($info,true);
            return $info['media_id'];
        }
    }

    public function check_admenu_data($data){
        $arr = [];
        if($data['name_type'] == 1){
            if($data['type'] == 1){
                unset($data['img_url']);
                unset($data['img_name']);
                unset($data['title']);
                unset($data['desc']);
                unset($data['img_url1']);
                unset($data['img_name1']);
                unset($data['tz_url']);
            }else if($data['type'] == 2){
                $media_id = $this->upload_image($data);
                $arr['img_url'] = $data['img_url'];
                $arr['img_name'] = $data['img_name'];
                $arr['media_id'] = $media_id;
                $data['content'] = json_encode($arr);
                unset($data['img_url']);
                unset($data['img_name']);
                unset($data['title']);
                unset($data['desc']);
                unset($data['img_url1']);
                unset($data['img_name1']);
                unset($data['tz_url']);
            }else if($data['type'] == 3){
                $arr['img_url1'] = $data['img_url1'];
                $arr['img_name1'] = $data['img_name1'];
                $arr['title'] = $data['title'];
                $arr['desc'] = $data['desc'];
                $arr['tz_url'] = $data['tz_url'];
                $data['content'] = json_encode($arr);
                unset($data['img_url']);
                unset($data['img_name']);
                unset($data['title']);
                unset($data['desc']);
                unset($data['img_url1']);
                unset($data['img_name1']);
                unset($data['tz_url']);
            }
        }else if($data['name_type'] == 2){
            unset($data['img_url']);
            unset($data['img_name']);
            unset($data['title']);
            unset($data['desc']);
            unset($data['img_url1']);
            unset($data['img_name1']);
            unset($data['tz_url']);
            $data['type'] = '';
        }
        return $data;
    }

    public function edit_data_rest($data){
        if($data['name_type'] == 1){
            if($data['type'] != 1){
                $data['content'] = json_decode($data['content']);
            }
        }
        return $data;
    }

    public function arrayToObject($arr) {
        if(is_array($arr)) {
            return (object)array_map(__FUNCTION__, $arr);
        }else {
            return $arr;
        }
    }

    public function  toarray(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }
}
